package com.itheima.udp2;

import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class UDPServer1 {

    public static void main(String[] args) throws Exception {

        //简单的UDP通信多发多收：服务端开发

        System.out.println("==========服务端启动==========");

        //1.创建接收端对象，绑定端口号
        DatagramSocket socket = new DatagramSocket(8080);

        //2.创建一个数据包对象负责接收数据
        byte[] bytes = new byte[1024 * 64];
        DatagramPacket packet = new DatagramPacket(bytes, bytes.length);

        while (true) {

            //3.调用接收方法，将数据接收到数据包对象的字节数组中去
            socket.receive(packet);     //等待式接收数据

            //4.查看数据是否收到
            int len = packet.getLength();
            String data = new String(bytes, 0, len);
            System.out.println("服务端接收到了：" + data);

            //获取发送端的地址和端口号
            System.out.println("发送端的地址：" + packet.getAddress().getHostAddress());
            System.out.println("发送端的端口号：" + packet.getPort());

            System.out.println("-----------------------------------------");
        }

    }
}
